package com.ruoyi.wxorali.service.impl;

import com.ruoyi.wxorali.service.WAVTestService;
import com.ruoyi.wxorali.service.WxServletService;
import jakarta.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WxServletServiceImpl implements WxServletService {

	@Override
	public String getPhoto(HttpServletRequest request, String Picurl) {
		{ // 对字节数组字符串进行Base64解码并生成图片
			SimpleDateFormat sdfo = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String dateo=sdfo.format(new Date());
			String filename ="/upload/" +dateo + ".jpg";
			String imgFilePath=request.getSession().getServletContext().getRealPath(filename);
			String filepath=request.getSession().getServletContext().getRealPath("/upload");
			File fileo=new File(filepath);
			if(!fileo.exists()){//如果文件夹不存在
				fileo.mkdir();//创建文件夹
			}
			Date date = new Date(System.currentTimeMillis() - 1000 * 60);
			File folder = new File(filepath);
			File[] files = folder.listFiles();
			for (int i=0;i<files.length;i++){
				File file = files[i];
				if (new Date(file.lastModified()).before(date)){
					file.delete();
				}
			}
			URL url = null;
			try {
				url = new URL(Picurl);
				DataInputStream dataInputStream = new DataInputStream(url.openStream());
				File file3=new File(imgFilePath);
				if (!file3.exists()) {
					file3.createNewFile();
				}
				FileOutputStream fileOutputStream = new FileOutputStream(file3);
				ByteArrayOutputStream output = new ByteArrayOutputStream();

				byte[] buffer = new byte[1024];
				int length;

				while ((length = dataInputStream.read(buffer)) > 0) {
					output.write(buffer, 0, length);
				}
				fileOutputStream.write(output.toByteArray());
				dataInputStream.close();
				fileOutputStream.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();

			}
			return filename;

		}
	}
}
